﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using CCWin;
using CCWin.SkinControl;
using GroupChat2013.Entity;
using CCWin.Win32;
using CCWin.Win32.Const;
using GroupChat2013.Common;
using GroupChat2013.Logic.Interface;
using GroupChat2013.Logic;
using System.Collections;
using System.Threading;

namespace GroupChat2013.Main
{
    public partial class FrmChatBox : CCSkinMain
    {
        #region 变量

        int orgHeight = 45;
        int itemHeight = 28;

        private ChatMessageItem m_NotifyItem;
        public int NotifyItemCount
        {
            get { return m_NotifyItem.SubItems.Count; }
        }

        public ChatMessageSubItem this[int index]
        {
            get { return m_NotifyItem.SubItems[index]; }
        }

        #endregion

        #region 事件

        public event Action DoubleClickItemHandler;

        public event Action ReceiveNewUnReadMsgHandler;

        #endregion

        #region 构造函数

        /// <summary>
        /// 构造函数
        /// </summary>
        public FrmChatBox()
        {
            InitializeComponent();
            SetStyles();
            // Window Style
            this.FormBorderStyle = FormBorderStyle.None;
            this.WindowState = FormWindowState.Minimized;
            //this.Show();
            this.Hide();
            this.WindowState = FormWindowState.Normal;
            this.ShowInTaskbar = false;
            this.TopMost = true;
            this.MaximizeBox = false;
            this.MinimizeBox = false;
            this.ControlBox = false;

            m_NotifyItem = new ChatMessageItem("消息盒子");
            this.Load += new EventHandler(FrmChatBox_Load);
        }

        #endregion

        public void InitMessageBox()
        {
            m_NotifyItem.SubItems.Clear();
            m_NotifyItem.IsOpen = true;
            chatMessageBox.Items.Add(m_NotifyItem);
            //for (int j = 0; j < 2; j++)
            //{
            //    ChatMessageSubItem subItem = new ChatMessageSubItem(j.ToString(), "NicName" + j, "联系人" + j, "我的个性签名,我的个性签名,我的个性签名", ChatType.User);
            //    subItem.HeadImage = Image.FromFile("head/" + 1 + ".png");
            //    subItem.ID = ((1 + 1) * (j + 1)).ToString();
            //    subItem.Status = (ChatMessageSubItem.UserStatus)(j % 6);
            //    if (j % 2 == 0)
            //        subItem.ChatType = ChatType.User;
            //    else
            //        subItem.ChatType = ChatType.Group;
            //    m_NotifyItem.SubItems.AddAccordingToStatus(subItem);
            //}
        }

        #region 窗体相关事件

        void FrmChatBox_Load(object sender, EventArgs e)
        {
            //检测鼠标是否在消息盒子内，果然不在隐藏消息盒子
            tmChatBox.Interval = 250;
            tmChatBox.Tick += (s, et) =>
            {
                Point pt = new Point();
                WinApi.GetCursorPos(out pt);
                Rectangle r = this.Bounds;
                r.Height = r.Height + 40;
                if (!r.Contains(pt))
                {
                    tmChatBox.Stop();
                    this.Hide();
                    return;
                }
            };

            //当接受到窗体打开事件后，删除消息提示
            EngineContext.Current.ChatManager.NoticeChatOpenedHandler += (x) =>
            {
                ChatMessageSubItem subItem = null;

                foreach (ChatMessageSubItem item in m_NotifyItem.SubItems)
                {
                    if (item.ID == x)
                    {
                        subItem = item;
                        break;
                    }
                }

                if (subItem != null)
                {
                    m_NotifyItem.SubItems.Remove(subItem);

                    if (DoubleClickItemHandler != null)
                        DoubleClickItemHandler();
                }
            };
        }

        #endregion

        #region 打开聊天窗口

        private void chatMessageBox_DoubleClickSubItem(object sender, CCWin.SkinControl.ChatMessageEventArgs e)
        {
            ChatMessageSubItem item = e.SelectSubItem;
            item.IsTwinkle = false;

            m_NotifyItem.SubItems.Remove(item);
            ResetHight();
            this.Hide();

            if (item.ChatType == ChatType.User)
            {
                ShowFrmChat(item);
            }
            else if (item.ChatType == ChatType.Group)
            {
                ShowFrmGroup(item);
            }

            if (DoubleClickItemHandler != null)
                DoubleClickItemHandler();
        }

        /// <summary>
        /// 显示私聊
        /// </summary>
        /// <param name="item"></param>
        public static void ShowFrmChat(ChatMessageSubItem item)
        {
            IChat chat = EngineContext.Current.ChatManager[item.ID];

            if (chat != null)
            {
                chat.Show();
                chat.Activate();
            }
            else
            {
                FriendInfo friendInfo = new FriendInfo()
                {
                    userInfoId = item.ID.ToString(),
                    loginName = item.DisplayName
                };

                FrmChat fChat = new FrmChat(friendInfo);
                EngineContext.Current.ChatManager.AddChat(item.ID, fChat);
                fChat.Text = "与 " + item.DisplayName + " 对话中";
                fChat.Show();
            }
        }

        /// <summary>
        /// 显示群聊
        /// </summary>
        /// <param name="item"></param>
        public static void ShowFrmGroup(ChatMessageSubItem item)
        {
            IChat chat = EngineContext.Current.ChatManager[item.ID];

            if (chat != null)
            {
                chat.Show();
                chat.Activate();
            }
            else
            {
                GroupInfo groupInfo = new GroupInfo()
                {
                    groupId = item.ID.ToString(),
                    groupName = item.DisplayName
                };

                FrmGroup fGroup = new FrmGroup(groupInfo);
                EngineContext.Current.ChatManager.AddChat(item.ID, fGroup);
                fGroup.Text = "与 " + item.DisplayName + " 群中";
                fGroup.Show();
            }
        }

        #endregion

        #region 公用方法

        /// <summary>
        /// 添加一个项
        /// </summary>
        public void AddItem(string id, string name, string unread, ChatType chatType)
        {
            foreach (ChatMessageSubItem item in m_NotifyItem.SubItems)
            {
                if (item.ID == id)
                {
                    item.UnReadCount = unread;
                    return;
                }
            }

            ChatMessageSubItem subItem=new ChatMessageSubItem();
            if (chatType == ChatType.Group)
            {
                subItem.HeadImage = Image.FromFile(GroupChat2013.Common.Helper.CombinePath(@"head\group.PNG"));
            }
            else
            {
                subItem.HeadImage = Image.FromFile(GroupChat2013.Common.Helper.CombinePath(@"head\1.png"));
            }
            subItem.ID = id;
            subItem.DisplayName = name;
            subItem.NicName = name;
            subItem.ChatType = chatType;
            subItem.UnReadCount = unread;

            m_NotifyItem.SubItems.AddAccordingToStatus(subItem);

            ResetHight();

            if (ReceiveNewUnReadMsgHandler != null)
                ReceiveNewUnReadMsgHandler();
        }

        /// <summary>
        /// 删除项
        /// </summary>
        /// <param name="uid"></param>
        public void RemoveItem(params int[] uid)
        {
            ResetHight();
        }

        /// <summary>
        /// 删除指定项 并返回该项
        /// </summary>
        /// <param name="index"></param>
        /// <returns></returns>
        public ChatMessageSubItem RemoveAt(int index)
        {
            ChatMessageSubItem item = m_NotifyItem.SubItems[index];
            if (item != null)
                m_NotifyItem.SubItems.Remove(item);
            ResetHight();
            return item;
        }

        /// <summary>
        /// 重新设置高度 
        /// </summary>
        public void ResetHight()
        {
            int count = m_NotifyItem.SubItems.Count > 10 ? 10 : m_NotifyItem.SubItems.Count;

            this.chatMessageBox.Height = itemHeight * count + 3;
            this.Height = orgHeight + this.chatMessageBox.Height;

        }

        /// <summary>
        /// 显示消息盒子
        /// </summary>
        /// <param name="x"></param>
        /// <param name="y"></param>
        public void Show(int x, int y)
        {
            if (this.m_NotifyItem.SubItems.Count > 0)
            {
                this.Focus();
                Point pt = new Point(x, y);
                this.Location = pt;
                this.Text = string.Format("消息盒子({0})", this.m_NotifyItem.SubItems.Count);
                this.Show();

                this.tmChatBox.Start();
            }
        }

        /// <summary>
        /// 隐藏消息盒子
        /// </summary>
        public new void Hide()
        {
            base.Hide();
            this.tmChatBox.Stop();
        }

        #endregion

        #region 私有方法

        private void SetStyles()
        {
            SetStyle(
                ControlStyles.UserPaint |
                ControlStyles.AllPaintingInWmPaint |
                ControlStyles.OptimizedDoubleBuffer |
                ControlStyles.ResizeRedraw |
                ControlStyles.DoubleBuffer, true);
            //强制分配样式重新应用到控件上
            UpdateStyles();
        }

        #endregion

        private void skinLabel1_Click(object sender, EventArgs e)
        {
            foreach (ChatMessageSubItem item in m_NotifyItem.SubItems)
            {
                if (item.ChatType == ChatType.User)
                {
                    ShowFrmChat(item);
                }
                else if (item.ChatType == ChatType.Group)
                {
                    ShowFrmGroup(item);
                }
            }

            ResetHight();
            this.Hide();

            if (DoubleClickItemHandler != null)
                DoubleClickItemHandler();
        }
    }
}
